/**
 * Cross-platform browser opening functionality
 * Uses platform-specific commands instead of external dependencies
 */
import { spawn } from 'child_process';

const PLATFORM_COMMANDS = {
  win32: 'start',
  darwin: 'open', 
  linux: 'xdg-open'
};

/**
 * Get platform-specific browser command
 * @param {string} platform - Process platform (win32, darwin, linux)
 * @returns {string} Platform command
 */
export function getBrowserCommand(platform = process.platform) {
  const command = PLATFORM_COMMANDS[platform];
  if (!command) {
    throw new Error(`Unsupported platform: ${platform}`);
  }
  return command;
}

/**
 * Validate URL format
 * @param {string} url - URL to validate
 * @returns {boolean} Is valid URL
 */
export function isValidUrl(url) {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
}

/**
 * Open URL in default browser
 * @param {string} url - URL to open
 * @param {Object} options - Options
 * @param {boolean} options.dryRun - Don't actually open, just validate
 * @returns {Promise<{success: boolean, url: string}>} Result
 */
export async function openUrl(url, options = {}) {
  if (!isValidUrl(url)) {
    throw new Error(`Invalid URL format: ${url}`);
  }

  const { dryRun = false } = options;
  
  if (dryRun) {
    return { success: true, url };
  }

  const command = getBrowserCommand();
  const args = command === 'start' ? ['', url] : [url];

  return new Promise((resolve, reject) => {
    const child = spawn(command, args, {
      detached: true,
      stdio: 'ignore',
      shell: true
    });

    child.on('error', (error) => {
      reject(new Error(`Failed to open browser: ${error.message}`));
    });

    child.unref();
    resolve({ success: true, url });
  });
}